﻿using System.IO;
using HttpApiGateway.Collect;
using HttpApiGateway.FileUp.Interface;
using HttpApiGateway.Interface;
using HttpService;
using HttpService.Handler;
using RpcHelper;

namespace HttpApiGateway.Handler
{
    internal class HttpBlockUpHandler : BasicHandler, IApiHandler
    {
        private IBlockUpTask _Task;
        private int _BlockIndex = -1;
        private IService _ApiService = null;
        public HttpBlockUpHandler(string uri, bool isRegex) : base(uri, 99, isRegex)
        {
        }

        protected sealed override bool InitHandler()
        {
            string fileId = this.Request.QueryString.Get("fileId");
            string index = this.Request.QueryString.Get("index");
            if (fileId.IsNull() || index.IsNull())
            {
                this.Response.SetHttpStatus(System.Net.HttpStatusCode.Forbidden);
                return false;
            }
            else if (!fileId.Validate(RpcHelper.Validate.ValidateFormat.Guid) || !int.TryParse(index, out this._BlockIndex))
            {
                this.Response.SetHttpStatus(System.Net.HttpStatusCode.Forbidden);
                return false;
            }
            else if (!BlockUpCollect.GetTask(fileId, out this._Task))
            {
                this.Response.SetHttpStatus(System.Net.HttpStatusCode.Forbidden);
                return false;
            }
            this._ApiService = new ApiService(this, this._Task.ServerName);
            if (!this._Task.CheckBlockIndex(this._BlockIndex))
            {
                this._ApiService.Reply();
                return false;
            }
            return true;
        }
        public override Stream GetSaveStream(UpFileParam param)
        {
            return this._Task.GetStream(this._BlockIndex);
        }
        protected override bool CheckCache(string etag, string toUpdateTime)
        {
            return false;
        }
        public override void Execute()
        {
            this._Task.WriteUpFile(this.Request.Files[0], this._BlockIndex);
            this._ApiService.Reply();
        }
        public override bool VerificationFile(UpFileParam param, long fileSize)
        {
            return true;
        }

        public override bool CheckUpFile(UpFileParam param, int num)
        {
            return num <= 1;
        }
    }
}
